package com.fxugph.components
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.TextEvent;
	import flash.text.ReturnKeyLabel;
	
	import mx.binding.utils.BindingUtils;
	import mx.binding.utils.ChangeWatcher;
	import mx.collections.ArrayCollection;
	import mx.collections.IList;
	
	import spark.components.Button;
	import spark.components.List;
	import spark.components.TextInput;
	import spark.components.supportClasses.SkinnableComponent;
	import spark.events.IndexChangeEvent;
	
	
	[SkinState("input")]
	
	[SkinState("inputWithResults")]
	
	public class SearchInput extends SkinnableComponent
	{
		
		[SkinPart]
		public var input:TextInput;
		
		[SkinPart]
		public var resultList:List;
		
		public function SearchInput()
		{
			super();
		}
		
		public var results:Array = [];
		
		[Bindable]
		public var suggestedResults:ArrayCollection;
		
		private var suggestedResultsWatcher:ChangeWatcher;
		

		override protected function partAdded(partName:String, instance:Object):void
		{
			if(instance == input)
			{
				input.addEventListener(KeyboardEvent.KEY_DOWN, textInputHandler);
			}
			else if(instance == resultList)
			{
				resultList.addEventListener(IndexChangeEvent.CHANGE, selectionChangeHandler);
				suggestedResultsWatcher = BindingUtils.bindProperty(resultList, "dataProvider", this, "suggestedResults");
			}
		}
		
		override protected function partRemoved(partName:String, instance:Object):void
		{
			if(instance == resultList)
			{
				resultList.removeEventListener(IndexChangeEvent.CHANGE, selectionChangeHandler);
				suggestedResultsWatcher.unwatch();
			}
		}
		
		protected function selectionChangeHandler(event:IndexChangeEvent):void
		{
			if(resultList.selectedItem)
			{
				input.text = String(resultList.selectedItem);
				suggestedResults = null;
			}
			
			invalidateSkinState();
		}
		
		protected function textInputHandler(event:Event):void
		{
			var suggestedResultsTmp:Array = [];
			
			if(input.text && input.text.length > 0)
			{
				for each(var result:String in results)
				{
					if(result.indexOf(input.text) != -1)
						suggestedResultsTmp.push(result);
				}
				
				suggestedResults = new ArrayCollection(suggestedResultsTmp);
			}
			else
				suggestedResults = null;
			
		
			invalidateSkinState();
		}
		
		override protected function getCurrentSkinState():String
		{
			
			if(suggestedResults && suggestedResults.length > 0)
			{
				return "inputWithResults";
			}
			else
				return "input";
			
		}
		
		
		
	}
}